package com.runen.infinitemovement.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.king.zxing.util.CodeUtils;
import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.adapter.HitCardAdapter;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.ChallengeAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.HitCardAdapterEntity;
import com.runen.infinitemovement.model.entity.HitCardEntity;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.infinitemovement.tool.notchtool.NotchTools;
import com.runen.infinitemovement.tool.notchtool.core.NotchProperty;
import com.runen.infinitemovement.tool.notchtool.core.OnNotchCallBack;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.infinitemovement.widget.popupwind.SharePoppupWindow;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Create by LiaoDuanHong
 * Create on
 */
public class PunchCardActivity extends BaseActivity {
    @BindView(R.id.tv_copy_writing)
    EditText tv_copy_writing;
    @BindView(R.id.tv_year)
    TextView tv_year;
    @BindView(R.id.tv_month_day)
    TextView tv_month_day;
    @BindView(R.id.tv_description)
    TextView tv_description;
    @BindView(R.id.rci_header)
    RoundedCornersImage rci_header;
    @BindView(R.id.tv_days)
    TextView tv_days;
    @BindView(R.id.tv_miles)
    TextView tv_miles;
    @BindView(R.id.iv_code)
    ImageView iv_code;
    @BindView(R.id.iv_background)
    ImageView iv_background;
    @BindView(R.id.rcv_background)
    RecyclerView rcv_background;
    @BindView(R.id.tv_hit_card)
    TextView tv_hit_card;
    @BindView(R.id.ll_save)
    LinearLayout ll_save;
    @BindView(R.id.v_zhezhao)
    View v_zhezhao;
    @BindView(R.id.rl_title)
    LinearLayout rl_title;
    @BindView(R.id.tv_name)
    TextView tv_name;

    public static final String FORMAT_YEAR = "yyyy";
    public static final String FORMAT_MONTH_DAY = "MM.dd";

    private static final int REQUEST_STATE_CODE = 1010;
    private Bitmap mBitmap;
    private String imagePath;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_punch_card;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        v_zhezhao.setVisibility(View.GONE);
        //适配刘海屏
        NotchTools.getFullScreenTools().translucentStatusBar(this, new OnNotchCallBack() {
            @Override
            public void onNotchPropertyCallback(NotchProperty notchProperty) {
//                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) rl_title.getLayoutParams();
//                layoutParams.topMargin = CommonUtil.getStatusBarHeight(PunchCardActivity.this);
//                rl_title.setLayoutParams(layoutParams);
                rl_title.setPadding(0, CommonUtil.getStatusBarHeight(PunchCardActivity.this), 0, 0);
            }
        });
//        String str = "https://h5.futmarch.cn/appDownload?" + UserAPI.getUserId();
        String url = String.format(Constant.INVIT_FRIEND, UserAPI.getUserId());
        iv_code.setImageBitmap(CodeUtils.createQRCode(url, 600));
        initData();
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    private void initData() {
        showDialog();
        new ChallengeAPI().hitCardInfo(new BaseResultCallback<HitCardEntity>() {
            @Override
            public void onResponse(HitCardEntity response) {
                dismissDialog();
                if (response.code == 0) {
                    if (response.data != null) {
                        setView(response.data);
                    }
                } else {
                    ToastUtils.showShort(response.msg);
                }
            }
        });
    }

    private void saveHitCardRecord() {
        new ChallengeAPI().saveHitCardRecord(new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                if (response.getCode() == 0) {
                    EventBus.getDefault().post(new EventBusEntity(EventBusEntity.CODE_107));
                }
            }
        });
    }

    private void setView(HitCardEntity.DataBean data) {
        if (!TextUtils.isEmpty(data.headImgUrl)) {
            GlideUtils.loadImage(this, data.headImgUrl, rci_header);
        }
//        if (!TextUtils.isEmpty(data.qrCodeImage)) {
//            GlideUtils.loadImage(this, data.qrCodeImage, iv_code);
//        }
        if (data.hitCardImageList != null && data.hitCardImageList.size() > 0) {
            GlideUtils.loadImage(this, data.hitCardImageList.get(0), iv_background);
        }
        tv_copy_writing.setEnabled(false);
        tv_copy_writing.setText(data.hitCardCopywriting.replace("\r", "\n"));
        tv_description.setText(data.hitCardDescription);
        tv_days.setText(data.day + "");
        tv_miles.setText(CommonUtil.Double2position(data.mileage) + "");
        tv_name.setText(data.nickname);
        if (tv_name.getText().toString().length() > 6) {
            tv_name.setText(tv_name.getText().toString().substring(0, 6) + "...");
        }


        tv_year.setText(getStringDate(FORMAT_YEAR));
        tv_month_day.setText(getStringDate(FORMAT_MONTH_DAY));

        LinearLayoutManager llm = new LinearLayoutManager(this);
        llm.setOrientation(RecyclerView.HORIZONTAL);
        rcv_background.setLayoutManager(llm);
        HitCardAdapter adapter = new HitCardAdapter(this);
        rcv_background.setAdapter(adapter);
        List<HitCardAdapterEntity> list = new ArrayList<>();
        for (String s : data.hitCardImageList) {
            if (list.size() == 0) {
                list.add(new HitCardAdapterEntity(s, true));
            } else {
                list.add(new HitCardAdapterEntity(s, false));
            }
        }
        adapter.addData(list);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter1, @NonNull View view, int position) {
                for (HitCardAdapterEntity entity : adapter.getData()) {
                    entity.isSelect = false;
                }
                adapter.getData().get(position).isSelect = true;
                GlideUtils.loadImage(PunchCardActivity.this, adapter.getData().get(position).url, iv_background);
                adapter.notifyDataSetChanged();
            }
        });
    }

    @OnClick({R.id.btn_finish, R.id.tv_hit_card})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_finish:
                finish();
                break;
            case R.id.tv_hit_card:
                v_zhezhao.setVisibility(View.VISIBLE);
                SharePoppupWindow sharePoppupWindow = SharePoppupWindow.getInstance(PunchCardActivity.this);
                sharePoppupWindow.setBitmap(savePoster());
                sharePoppupWindow.setOnClick(new SharePoppupWindow.OnClick() {
                    @Override
                    public void savePic(Bitmap bitmap) {
                        saveLocalPic(bitmap);
                        v_zhezhao.setVisibility(View.GONE);
                        saveHitCardRecord();
                    }

                    @Override
                    public void hitCard() {
                        v_zhezhao.setVisibility(View.GONE);
                        saveHitCardRecord();
                    }

                    @Override
                    public void dismiss() {
                        v_zhezhao.setVisibility(View.GONE);
                    }

                    @Override
                    public String imagePath(Bitmap bitmap) {
                        return saveLocalPic(bitmap);
                    }
                });
                sharePoppupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        v_zhezhao.setVisibility(View.GONE);
                    }
                });
                sharePoppupWindow.show(1.0f);
                break;
        }
    }

    public String getStringDate(String format) {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 生成海报图片
     */
    private Bitmap savePoster() {
//        // 1.View截图
//        ll_save.destroyDrawingCache();
//        ll_save.setDrawingCacheEnabled(true);
//        // 重新测量View
//        ll_save.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
//                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
//        // 2.创建一个Bitmap
//        Bitmap mBitmap = ll_save.getDrawingCache();
//        return mBitmap;

        //获取当前屏幕的大小
        int width = getWindow().getDecorView().getRootView().getWidth();
        int height = getWindow().getDecorView().getRootView().getHeight();
        //生成相同大小的图片（用来存储截屏后生成的bitmap对象）
        Bitmap temBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        //找到当前页面的根布局（需要截屏的View）
        View view = ll_save;
        //设置缓存
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        //从缓存中获取当前屏幕的图片
        temBitmap = view.getDrawingCache().copy(Bitmap.Config.ARGB_8888, false);
        //将截屏图片保存至本地
//        saveToLocal(temBitmap);
        //销毁当前屏幕图片的缓存
        view.destroyDrawingCache();
        view.setDrawingCacheEnabled(false);
        return temBitmap;
    }

    private String saveLocalPic(Bitmap bitmap) {
        // 3.保存到SD卡
        if (bitmap != null) {
            this.mBitmap = bitmap;
            //判断是否为Android 6.0 以上的系统版本，如果是，需要动态添加权限
            if (Build.VERSION.SDK_INT >= 23) {
                requestPermissions(bitmap);
            } else {
                saveToLocal(bitmap);
            }
        }
        return imagePath;
    }

    private void requestPermissions(Bitmap bitmap) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, REQUEST_STATE_CODE);
        } else {
            saveToLocal(bitmap);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_STATE_CODE:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    saveToLocal(mBitmap);
                } else {
                    ToastUtils.showLong("权限授予失败，请重新授予");
                    return;
                }
                break;
            default:
                break;
        }
    }

    /**
     * 保存一张Bitmap图到本地
     */
    private void saveToLocal(Bitmap bitmap) {
        if (Build.VERSION.SDK_INT >= 30) {
            saveImageToGallery(PunchCardActivity.this, bitmap);
        } else {
            try {
                File appDir = new File(Environment.getExternalStorageDirectory(), "sharePoster");
                // 没有目录创建目录
                if (!appDir.exists()) {
                    appDir.mkdir();
                }
                Long mImageTime = System.currentTimeMillis();
                String imageDate = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date(mImageTime));
                String SCREENSHOT_FILE_NAME_TEMPLATE = "wyyd_%s.png";//图片名称，以"wuyayundong_"+时间戳命名
                String mImageFileName = String.format(SCREENSHOT_FILE_NAME_TEMPLATE, imageDate);
                File file = new File(appDir, mImageFileName);

                FileOutputStream out;
                try {
                    out = new FileOutputStream(file);
                    if (bitmap.compress(Bitmap.CompressFormat.PNG, 90, out)) {
                        out.flush();
                        out.close();
                        // 通知图库更新
                        Uri uri = Uri.fromFile(file);
                        Intent scannerIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
                        sendBroadcast(scannerIntent);
                        imagePath = file.getPath();
                        ToastUtils.showLong("保存图片到相册成功");
                        Log.e("123456789", "saveToLocal: " + file.getPath());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * android 11及以上保存图片到相册
     *
     * @param context
     * @param image
     */
    @RequiresApi(api = Build.VERSION_CODES.R)
    public void saveImageToGallery(Context context, Bitmap image) {
        Long mImageTime = System.currentTimeMillis();
        String imageDate = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date(mImageTime));
        String SCREENSHOT_FILE_NAME_TEMPLATE = "wyyd__%s.png";//图片名称，以"wuyayundong_"+时间戳命名
        String mImageFileName = String.format(SCREENSHOT_FILE_NAME_TEMPLATE, imageDate);

        final ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES
                + File.separator + "sharePoster"); //Environment.DIRECTORY_SCREENSHOTS:截图,图库中显示的文件夹名。"dh"
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, mImageFileName);
        values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
        values.put(MediaStore.MediaColumns.DATE_ADDED, mImageTime / 1000);
        values.put(MediaStore.MediaColumns.DATE_MODIFIED, mImageTime / 1000);
        values.put(MediaStore.MediaColumns.DATE_EXPIRES, (mImageTime + DateUtils.DAY_IN_MILLIS) / 1000);
        values.put(MediaStore.MediaColumns.IS_PENDING, 1);

        ContentResolver resolver = context.getContentResolver();

        final Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        try {
            // First, write the actual data for our screenshot
            try (OutputStream out = resolver.openOutputStream(uri)) {
                if (!image.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                    throw new IOException("Failed to compress");
                }
            }
            // Everything went well above, publish it!
            values.clear();
            values.put(MediaStore.MediaColumns.IS_PENDING, 0);
            values.putNull(MediaStore.MediaColumns.DATE_EXPIRES);
            resolver.update(uri, values, null, null);
            imagePath = Environment.DIRECTORY_PICTURES + File.separator + "sharePoster/" + mImageFileName;
            Log.e("123456789", "saveImageToGallery: " + imagePath);
            ToastUtils.showLong("保存图片到相册成功");
        } catch (IOException e) {
            resolver.delete(uri, null);
        }
    }
}
